package com.freewater.javabase.demo.unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class UnSafeDemo {
    public static void main(String[] args) {
        //Unsafe unsafe = Unsafe.getUnsafe(); // will exception
        //Unsafe unSafe = getUnSafe();
        //System.out.println(unSafe);
        User user = new User();
        user.name = "张三";

        try {
            System.out.println(user.getName());
            modifyUserName(user, "李四");
            System.out.println(user.getName());
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    public static Unsafe getUnSafe() {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            Unsafe unsafe = (Unsafe) field.get(null);
            return unsafe;
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void modifyUserName(User user, String newName) throws NoSuchFieldException {
        Unsafe unSafe = getUnSafe();
        Field name = user.getClass().getDeclaredField("name");
        long fieldOffset = unSafe.objectFieldOffset(name);
        unSafe.putObject(user, fieldOffset, newName);
    }

    public static class User {
        private String name;

        public String getName() {
            return this.name;
        }
    }
}
